package com.zdd.ehe.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdd.ehe.entity.Role;
import com.zdd.ehe.entity.User;
import com.zdd.ehe.result.Result;
import com.zdd.ehe.service.IPermissionService;
import com.zdd.ehe.service.IRoleService;
import com.zdd.ehe.service.IUserService;
import com.zdd.ehe.util.PBKDF2Util;
import com.zdd.ehe.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ZhuiZhu
 * @since 2023-03-13
 */
@Api(tags = "用户管理模块")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;

    @ApiOperation("获取所有用户（不分页）接口")
    @GetMapping("/getalluser")
    public Result getAllUser(){
        List<User> userList = userService.list();
        // 类型转换
        List<UserVo> userVoList = convertList(userList);

        return Result.success("查询成功!",userVoList);
    }

    @ApiOperation("通过id获取用户接口")
    @GetMapping("/getuserbyid")
    public Result getUserById(@RequestParam("id") String id){
        User user = userService.getById(id);
        if(user != null){
            UserVo userVo = convertObject(user);

            return Result.success("查询成功!",userVo);
        }else{
            return Result.error("查询失败");
        }

    }

    @ApiOperation("获取所有用户接口（分页）接口")
    @PostMapping("/getalluserbypage")
    public Result getAllUserByPage(@RequestParam("page") Integer page,@RequestParam("pageSize") Integer pageSize){
        Page<User> pagex = new Page<>(page,pageSize);
        Page<User> pageResult = userService.getalluserbypage(pagex);
        if(pageResult.getSize() == 0){
            return Result.error(4001,"无数据");
        }

        // 获取数据
        List<User> userList = pageResult.getRecords();
        // 类型转换
        List<UserVo> userVoList = convertList(userList);

        Map<String,Object> data = new HashMap<>();
        data.put("userList",userVoList);
        data.put("total",pageResult.getTotal());
        data.put("size",pageResult.getSize());
        data.put("current",pageResult.getCurrent());
        data.put("pages",pageResult.getPages());
        return Result.success("查询成功",data);
    }

    @ApiOperation("通过username获取用户列表接口")
    @GetMapping("/getuserbyusername")
    public Result getUserByUserName(@RequestParam("userName") String userName){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("user_name", userName);
        List<User> userlist = userService.list(wrapper);
        if(userlist.size() != 0){
            List<UserVo> userVoList = convertList(userlist);
            Map<String,Object> data = new HashMap<>();
            data.put("userList",userVoList);
            data.put("total",userVoList.size());
            data.put("size",10);
            data.put("current",1);
            data.put("pages",1);
            return Result.success("查询成功!",data);
        }else{
            return Result.error(4001,"未查询到该用户");
        }
    }


    @ApiOperation("更新用户信息接口（不带角色和权限）")
    @PostMapping("/updateuser")
    public Result updateUser(@RequestBody User user){
        if(user == null){
            return Result.error(4001,"参数异常");
        }

        if (!user.getPassword().equals("")){
            // 需要修改密码
            String salt = "";
            try {
                salt = PBKDF2Util.generateSalt();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }

            String password = "";
            try {
                password = PBKDF2Util.getEncryptedPassword(user.getPassword(),salt);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (InvalidKeySpecException e) {
                e.printStackTrace();
            }

            user.setPassword(password);
            user.setSalt(salt);

        }else{
            user.setPassword(null);
        }


        User userx = userService.getById(user.getId());
        if(userx == null){
            return Result.error(4002,"数据异常");
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("account", user.getAccount());
        User usery = userService.getOne(wrapper);

        if(usery != null){
            User user1 = userService.getById(user.getId());
            if(!usery.getAccount().equals(user1.getAccount())) {
                return Result.error(4005, "该账号已被注册");
            }
        }
        int result = userService.updateUser(user);
        if(result == -1){
            return Result.error(4003,"修改失败");
        }

        return Result.success("修改成功");
    }

    @ApiOperation("删除用户接口")
    @PostMapping("/deleteuserbyid")
    public Result deleteUserById(@RequestParam("id") Integer id){
        User user = userService.getById(id);
        if(user == null){
            return Result.error(4001,"用户编号错误");
        }
        user.setDel("0");
        int result = userService.updateUser(user);
        if(result == -1){
            return Result.error(4002,"删除失败");
        }
        return Result.success("删除成功");
    }


    @ApiOperation("重新启用用户账号接口")
    @PostMapping("/enableuserbyid")
    public Result enableUserById(@RequestParam("id") Integer id){
        User user = userService.getById(id);
        if(user == null){
            return Result.error(4001,"用户编号错误");
        }
        user.setDel("1");
        int result = userService.updateUser(user);
        if(result == -1){
            return Result.error(4002,"重新启用失败");
        }
        return Result.success("重新启用成功");
    }

    /**
     * User列表转UserVo列表，添加角色和权限
     * @param userList
     * @return
     */
    public List<UserVo> convertList(List<User> userList){
        List<UserVo> userVoList = new ArrayList<>();
        for(User user:userList){
            UserVo userVo = convertObject(user);
            userVoList.add(userVo);
        }
        return userVoList;
    }

    /**
     * User对象转UserVo对象
     * @param user
     * @return
     */
    public UserVo convertObject(User user){
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        // 获取用户角色
        List<String> roles = userService.getRoles(user.getId());
        // 获取用户权限
        List<String> permissions = new ArrayList<>();
        for(int i=0;i<roles.size();i++){
            List<String> permissionList = roleService.getPermissions(roles.get(i));
            for(int j=0;j<permissionList.size();j++){
                permissions.add(permissionList.get(j));
            }
        }
        // 添加角色和权限
        userVo.setRoles(roles);
        userVo.setPermissions(permissions);
        return userVo;
    }



}
